<?php

namespace App\Console\Commands;

use App\Models\Family;
use App\Models\Org;
use App\Models\Project;
use App\Models\Team;
use App\Models\User;
use App\Models\UserProject;
use App\Models\Volunteer;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class Stars extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'stars';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '星级管理';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //
        Log::info('refresh stars');

        $orgList = Org::where('open_stars', 1)->get();

        foreach($orgList as $value)
        {
            $volunteerStars = json_decode($value->volunteet_stars_config, true);

            //有配置志愿者星级
            if(is_array($volunteerStars))
            {
                foreach($volunteerStars as $k=>$val)
                {
                    $this->refreshVolunteerStarsVerify($value->id, $k, $val);
                }
            }

            $teamStars = json_decode($value->team_stars_config, true);

            //有配置志愿者星级
            if(is_array($teamStars))
            {
                foreach($teamStars as $k=>$val)
                {
                    $this->refreshTeamStarsVerify($value->id, $k, $val);
                }
            }

        }
    }

    private function refreshVolunteerStarsVerify($orgId, $stars, $score)
    {
        Log::info("refresh volunteer stars status orgId:{$orgId} stars:{$stars} score:{$score} ");
        Volunteer::where('org_id', $orgId)->where('stars', '<', $stars)->where('stars_verify_num', '<', $stars)->where('reward_time', '>=', $score)->update(['stars_verify_num'=>$stars, 'stars_verify_status'=>0]);
    }

    private function refreshTeamStarsVerify($orgId, $stars, $score)
    {
        Log::info("refresh team stars status orgId:{$orgId} stars:{$stars} score:{$score} ");
        Team::where('org_id', $orgId)->where('stars', '<', $stars)->where('stars_verify_num', '<', $stars)->where('reward_time', '>=', $score)->update(['stars_verify_num'=>$stars, 'stars_verify_status'=>0]);
    }
}
